package top.huxy.boot.config.argumentResolver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.huxy.boot.exception.NoCredentialsException;
import top.huxy.boot.model.entity.User;
import top.huxy.boot.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Classname UserArgumentResolver
 * @Description UserArgumentResolver
 * @Date 2021/9/9 14:21
 * @Created by huxy
 */
@Slf4j
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) {
            log.debug("request 不应该为null");
            throw0("未知错误,无权访问");
        }
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) throw0("未登录，无法访问");

        //从缓存获取
        Object user = redisTemplate.opsForValue().get(authorization);
        if(user==null) throw0("凭证过期，请重新登陆");
        return user;
    }

    public void throw0(String msg) {
        throw new NoCredentialsException(msg);
    }
}
